<script setup lang="ts">
import { ref, watch } from 'vue';
import type { QuestionItem } from '#/types/question';
import QuestionHeader from './question-header.vue';
import { QUESTION_STATUS } from '../../const';
import { $t } from '@vben/locales';    
interface Props {
  question: QuestionItem;
  questionIndex: number;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  updateStatus: [questionItem: QuestionItem, status: typeof QUESTION_STATUS.ANSWERED | typeof QUESTION_STATUS.UNANSWERED | typeof QUESTION_STATUS.MARKED,isMarked?:boolean];
  updateAnswer: [questionId: string | number, answer: any];
}>();

const selectedAnswer = ref<string>('');
const isMarked = ref(false);

// 初始化答案和状态
watch(() => props.question, (newQuestion) => {
  if (newQuestion.answer) {
    // const answer = JSON.parse(newQuestion.answer as string);
    const answer = newQuestion.answer || [] as any;
    selectedAnswer.value = answer.id;
  }
  isMarked.value = newQuestion.markDoubtful || false;
}, { immediate: true });

// 处理选项变化
const handleAnswerChange = (value: string) => {
  selectedAnswer.value = value;
  emit('updateAnswer', props.question.id, {id:value});
  emit('updateStatus', props.question, QUESTION_STATUS.ANSWERED,isMarked.value);
};

// 处理存疑操作
const handleMark = () => {
  isMarked.value = !isMarked.value;
  const status = isMarked.value ? QUESTION_STATUS.MARKED : (selectedAnswer.value ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED);
  emit('updateStatus', props.question, status,isMarked.value);
};

// 获取选项列表
const options = props.question.originalData?.options || [
  { id: 'true', name: $t('examCore.questions.true') },
  { id: 'false', name: $t('examCore.questions.false') }
];
</script>

<template>
  <div class="true-false-question" :data-question-id="question.id">
    <QuestionHeader 
      :question-index="questionIndex"
      :stem="question.originalData?.stem || ''"
      :score="question.originalData?.score || 0"
      :is-marked="isMarked"
      @mark="handleMark"
    />
    
    <!-- <div v-if="question.originalData?.stemImg" class="question-image mb-4">
      <img :src="question.originalData.stemImg" :alt="$t('examCore.questionImage')" class="max-w-full h-auto" />
    </div> -->

    <el-radio-group v-model="selectedAnswer" @change="handleAnswerChange" class="question-options ml-4">
        <el-radio :value="option.id" v-for="option in options" :key="option.id" class="w-full">
          <span class="option-label">{{ option.name }}</span>
        </el-radio>
    </el-radio-group>
  </div>
</template>

<style scoped>
.option-label {
  font-weight: 400;
  font-size: 12px;
}
</style> 
